package com.example.venue_reservation_service.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class RabbitMQConfig {

    // 定义延迟交换机（使用自定义x-delayed-message类型）
    @Bean
    public CustomExchange delayedExchange() {
        return new CustomExchange("delayed.exchange", "x-delayed-message",
                true,
                false,
                Map.of("x-delayed-type", "direct"));
    }

    // 定义延迟队列
    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable("delayed.queue").build();
    }

    // 绑定队列到交换机
    @Bean
    public Binding binding(Queue delayedQueue, CustomExchange delayedExchange) {
        return BindingBuilder.bind(delayedQueue)
                .to(delayedExchange)
                .with("delay.routing.key")
                .noargs();
    }

    // 添加聊天消息队列
    @Bean
    public Queue chatMessageQueue() {
        return new Queue("chat.message.queue");
    }

    // 配置RabbitTemplate用于JSON消息转换
    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}